// import Overlay from './Overlay'
export default class FbxModel {
  constructor ({ sandbox, url, position = { x: 0, y: 0, z: 0 }, scale = 1, enableCache = true }) {
    // super()
    this.sandbox = sandbox
    this.scene = sandbox.scene
    this.url = url
    this._position = position
    this._scale = scale
    this.enableCache = enableCache
    this.loader = new GC.FBXLoader()
    return this.initOverlay()
  }

  async initOverlay() {
    // this.overlay = await this.loader.loadAsync(this.url)
    this.overlay = await this.loader.loadResource(this.url, this.enableCache)
    this.overlay.traverse(child => {
      if (child.isObject3D) {
        child.castShadow = true
        child.receiveShadow = true
      }
    })
    const { x, y, z } = this._position
    this.overlay.position.set(x, y, z)
    const scaleArr = Array.isArray(this._scale) ? this._scale : [this._scale, this._scale, this._scale]
    this.overlay.scale.set(...scaleArr)
    this.scene.add(this.overlay)

    this.animations = this.overlay.animations
    this.mixer = new GC.AnimationMixer(this.overlay)
    this.mixer.addEventListener('finished', () => {
      console.log('结束')
      this._animationPlaying = false
    })
    return this
  }

  // const clock = new GC.Clock()
  get animationPlaying () {
    return this._animationPlaying || false
  }

  enableAnimation (params = { name: '', speed: 1, loop: true }) {
    this.stopAnimation()
    this._animationPlaying = true
    const { name = '', speed = 1, loop = true } = params

    this.mixer.timeScale = speed // 设置播放倍率
    const clock = new GC.Clock()
    this.animations.forEach((clip) => {
      if (!name || clip.name === name) {
        const action = this.mixer.clipAction(clip)
        action.loop = loop ? GC.LoopRepeat : GC.LoopOnce
        // action.clampWhenFinished = true
        action.play()
        action.paused = false
      }
    })
    this.updateIndex = this.sandbox.renderCalls.add(() => {
      if (this.mixer) {
        this.mixer.update(clock.getDelta())
      }
    })
  }

  stopAnimation () {
    this._animationPlaying = false
    if (this.mixer) {
      this.mixer.stopAllAction()
    }
    this.sandbox.renderCalls.remove(this.updateIndex)
  }

  zoomTo() {
    const box = new GC.Box3().setFromObject(this.overlay)
    const size = box.getSize(new GC.Vector3())
    const center = box.getCenter(new GC.Vector3())

    // 设置相机位置和朝向
    const maxSize = Math.max(size.x, size.y, size.z)
    const cameraDistance = maxSize * 1.0
    this.sandbox.camera.position.set(
      center.x + cameraDistance,
      center.y + cameraDistance / 2,
      center.z + cameraDistance / 2
    )
    this.sandbox.camera.lookAt(center.x, center.y, center.z)
  }
}
